package com.gr.controller;

import com.gr.entity.Brand;
import com.gr.entity.Phone;
import com.gr.service.BrandService;
import com.gr.service.PhoneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/phone")
public class PhoneController {
    @Autowired
    private PhoneService phoneService;
    @Autowired
    private BrandService brandService;
    @RequestMapping("/selectAllPhone")
    public String selectAllPhone(Model model){
        List<Phone> phones = phoneService.selectAll();
        model.addAttribute("phones",phones);
        return "/phone_list.jsp";
    }
    @RequestMapping("/selectAllPhoneAndBrand")
    public String selectAllPhoneAndBrand(Model model){
        List<Phone> phones = phoneService.selectAllPhoneAndBrand();
        int count= phoneService.selectPhoneCount();
        model.addAttribute("count",count);
        model.addAttribute("phones",phones);
        return "/phone_list.jsp";
    }
    @RequestMapping("/insertPhone")
    public String insertPhone(Phone phone){
        phoneService.insertPhone(phone);
        return "/phone/selectAllPhoneAndBrand.do";
    }
    @RequestMapping("/deletePhone")
    public String deletePhoneById(Integer id){
        phoneService.deletePhoneById(id);
        return "/phone/selectAllPhoneAndBrand.do";
    }
    @RequestMapping("/selectOnePhone")
    public String selectOnePhone(Integer id,Model model){
        Phone phone = phoneService.selectPhoneById(id);
        List<Brand> brands = brandService.selectAllBrand();
        model.addAttribute("brands",brands);
        model.addAttribute("phone",phone);
        return "/update.jsp";
    }
    @RequestMapping("/updatePhone")
    public String updatePhone(Phone phone,Model model){
        phoneService.updatePhone(phone);
        List<Brand> brands = brandService.selectAllBrand();
        model.addAttribute("brands",brands);
        model.addAttribute("phone",phone);
        return "/phone/selectAllPhoneAndBrand.do";
    }
    @RequestMapping("/multiDelete")
    public String multiDeletePhone(int[] ids){
        for (int i: ids) {
            phoneService.deletePhoneById(i);
        }
        return "/phone/selectAllPhoneAndBrand.do";
    }

}
